import axios from 'axios'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import { getStorage, removeStorage } from '../utils/auth'
import router from '../router/index'

// 创建请求实例
const $http = axios.create({
  baseURL: 'http://localhost:8888/api/private/v1',
  timeout: 5000,
})

// 请求拦截器
$http.interceptors.request.use(
  config => {
    // 进度条加载
    nprogress.start()

    // 已登录，每次请求都携带token
    const userInfo = getStorage('userInfo')
    if (userInfo) {
      config.headers.Authorization = userInfo.token
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截器
$http.interceptors.response.use(
  response => {
    // 进度条结束
    nprogress.done()
    // 服务器响应成功
    if (response.status === 200) {
      const res = response.data
      // 结果正确
      const statusArr = [200, 201, 204]
      if (statusArr.includes(res.meta.status)) {
        return res.data
      } else {
        // 结果错误
        Message.error(res.meta.msg)
        if (res.meta.status === 400 && res.meta.msg === '无效token') {
          removeStorage('userInfo')
          router.push('/login')
        }
        return Promise.reject(res.meta.msg)
      }
    }
  },
  err => {
    return Promise.reject(err)
  }
)

const $get = (url, params = {}) => $http.get(url, { params })

const $post = (url, data = {}, config = {}) => $http.post(url, data, config)

const $put = (url, data = {}, config = {}) => $http.put(url, data, config)

const $delete = (url, config = {}) => $http.delete(url, config)

export { $http, $get, $post, $put, $delete }
